use crate::controls::control_utils::show_messagebox;
use crate::globals::constants::*;
use windows::Win32::UI::WindowsAndMessaging::MB_ICONINFORMATION;
use windows_service::Result;
use windows_service::service::ServiceAccess;
use windows_service::service_manager::{ServiceManager, ServiceManagerAccess};

/// 启动服务
pub fn start_service() -> Result<()> {
    // 连接到服务管理器
    let manager_access = ServiceManagerAccess::CONNECT;
    let service_manager = ServiceManager::local_computer(None::<&str>, manager_access)?;

    // 打开服务
    let service_access = ServiceAccess::QUERY_STATUS | ServiceAccess::START;

    // 尝试打开服务
    let service = match service_manager.open_service(SERVICE_NAME, service_access) {
        Ok(service) => service,
        Err(e) => {
            // 提取错误代码
            let error_code = match &e {
                windows_service::Error::Winapi(io_error) => {
                    io_error.raw_os_error().unwrap_or(0) as u32
                }
                _ => 0,
            };
            show_messagebox(
                "启动服务 - 错误",
                &format!("无法打开服务！错误代码: {}", error_code),
                windows::Win32::UI::WindowsAndMessaging::MB_ICONWARNING,
            );
            return Err(e);
        }
    };

    // 启动服务
    match service.start::<&str>(&[]) {
        Ok(_) => {
            // 服务启动成功
            show_messagebox("启动服务", "服务启动成功！", MB_ICONINFORMATION);
        }
        Err(e) => {
            // 服务启动失败
            let error_code = match &e {
                windows_service::Error::Winapi(io_error) => {
                    io_error.raw_os_error().unwrap_or(0) as u32
                }
                _ => 0,
            };
            show_messagebox(
                "启动服务 - 错误",
                &format!("服务启动失败！错误代码: {}", error_code),
                windows::Win32::UI::WindowsAndMessaging::MB_ICONWARNING,
            );
            return Err(e);
        }
    }

    Ok(())
}
